package com.yanqu.road.server.gameplayer.module.giftKey;


import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.ePlayerAttrType;
import com.yanqu.road.entity.giftKey.GiftKeyInfo;
import com.yanqu.road.entity.giftKey.GiftKeyUse;
import com.yanqu.road.entity.giftKey.UserGiftKeyRedPacket;
import com.yanqu.road.logic.bussiness.giftKey.GiftKeyBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.AttributeModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class GiftKeyModule extends GeneralModule {

    private Map<String, UserGiftKeyRedPacket> userGiftKeyRedPacketMap;

    private List<GiftKeyUse> giftKeyUseList;

    private List<GiftKeyUse> needAddGiftKeyUseList;

    public GiftKeyModule(GamePlayer player) {
        super(player);
    }


    @Override
    public boolean loadData() {
        long removeValue = player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.GiftKeyMoveToUser);
 /*       if(0L == removeValue){
            giftKeyUseList = GiftKeyBussiness.getGiftKeyUseList(player.getUserId());
            boolean success = GiftKeyBussiness.addUserGiftKeyUseList(giftKeyUseList);
            if(success){
                //什么时候迁移的
                player.getModule(AttributeModule.class).setAttribute(ePlayerAttrType.GiftKeyMoveToUser,System.currentTimeMillis());
            }
        }else{
        }*/
        giftKeyUseList = GiftKeyBussiness.getUserGiftKeyUseList(player.getUserId());
        needAddGiftKeyUseList = new ArrayList<>();
        userGiftKeyRedPacketMap = GiftKeyBussiness.getUserGiftKeyRedPacket(player.getUserId());
        return true;
    }

    public boolean isUseKey(String exchangeCode) {
        synchronized (giftKeyUseList) {
            for (GiftKeyUse userGiftKeyInfo : giftKeyUseList) {
                if (userGiftKeyInfo.getExchangeCode().equals(exchangeCode)) {
                    return true;
                }
            }
        }
        return false;
    }

    //同一个生成的configId的兑换码有对应使用的次数 2是动态码
    public boolean isOnceUseLimitKey(GiftKeyInfo giftKeyInfo) {
        if(giftKeyInfo.getCodeType() == 2){
            synchronized (giftKeyUseList) {
                int useSameCount = 0;
                for (GiftKeyUse giftKeyUse : giftKeyUseList) {
                    if (giftKeyUse.getConfigId() == giftKeyInfo.getConfigId()) {
                        useSameCount++;
                    }
                }
                if(useSameCount >= giftKeyInfo.getReceiveNum()){
                    return true;
                }
            }
        }
        return false;
    }

    //通用码的0是无上限，数值对应这个通用码总的能使用的次数 1是通用码
    public boolean isCommonUseLimitKey(GiftKeyInfo giftKeyInfo) {
        if(giftKeyInfo.getCodeType() == 1){
            synchronized (giftKeyUseList) {
                if(giftKeyInfo.getMaxLimit() == 0){
                    return false;
                }
                if(giftKeyInfo.getUseTimes() >= giftKeyInfo.getMaxLimit()){
                    return true;
                }
            }
        }
        return false;
    }

    public Map<String, UserGiftKeyRedPacket> getUserGiftKeyRedPacketMap() {
        return userGiftKeyRedPacketMap;
    }

    public void setUserGiftKeyRedPacketMap(Map<String, UserGiftKeyRedPacket> userGiftKeyRedPacketMap) {
        this.userGiftKeyRedPacketMap = userGiftKeyRedPacketMap;
    }

    public void addUserGiftKeyRedPacket(GiftKeyInfo giftKeyInfo) {
        if (giftKeyInfo.getPlayType() == 2) {
            // 复制参数并添加到map里面
            try {
                if (!userGiftKeyRedPacketMap.containsKey(giftKeyInfo.getExchangeCode())) {
                    UserGiftKeyRedPacket userGiftKeyRedPacket = new UserGiftKeyRedPacket();
                    userGiftKeyRedPacket.setUserId(player.getUserId());
                    userGiftKeyRedPacket.setKey(giftKeyInfo.getExchangeCode());
                    userGiftKeyRedPacket.setStartTime(System.currentTimeMillis());
                    userGiftKeyRedPacket.setSettings(giftKeyInfo.getSlideSettings());
                    userGiftKeyRedPacket.setLastReqTime(0);
                    userGiftKeyRedPacket.setRealGetIngots(0);
                    userGiftKeyRedPacket.setGetIngots(false);
                    userGiftKeyRedPacket.setInsertOption();
                    userGiftKeyRedPacketMap.put(giftKeyInfo.getExchangeCode(), userGiftKeyRedPacket);
                }
            } catch (Exception ex) {
                log.error("滑红包兑换码兑换失败");
            }
        }
    }

    /**
     * 添加使用的兑换码
     * @param giftKeyInfo
     */
    public void addGiftKeyUse(GiftKeyInfo giftKeyInfo) {
        synchronized (giftKeyUseList) {
            GiftKeyUse giftKeyUse = new GiftKeyUse();
            giftKeyUse.setConfigId(giftKeyInfo.getConfigId());
            giftKeyUse.setUserId(player.getUserId());
            giftKeyUse.setExchangeCode(giftKeyInfo.getExchangeCode());
            giftKeyUse.setUseTime(System.currentTimeMillis() / 1000);
            giftKeyUseList.add(giftKeyUse);
            needAddGiftKeyUseList.add(giftKeyUse);

            /**
             * 添加giftKey
             */
            if (giftKeyInfo.getPlayType() == 2) {
                addUserGiftKeyRedPacket(giftKeyInfo);
            }

        }
    }

    @Override
    public boolean afterLoadData() {
        return false;
    }

    @Override
    public void afterLogin() {
        for (UserGiftKeyRedPacket userGiftKeyRedPacket : userGiftKeyRedPacketMap.values()) {
            if (!userGiftKeyRedPacket.isGetIngots()) {
                getRedPacketReward(userGiftKeyRedPacket);
            }
        }
    }

    @Override
    public boolean saveData() {
        List<GiftKeyUse> tempNeedAddGiftKeyUseList = new ArrayList<>();
        synchronized (giftKeyUseList) {
            tempNeedAddGiftKeyUseList.addAll(needAddGiftKeyUseList);
            needAddGiftKeyUseList = new ArrayList<>();
        }
        //保存到server库的
        for (GiftKeyUse giftKeyUse : tempNeedAddGiftKeyUseList) {
            GiftKeyBussiness.addGiftKeyUse(giftKeyUse);
        }
        //保存到用户库
        GiftKeyBussiness.addUserGiftKeyUseList(tempNeedAddGiftKeyUseList);

        for (UserGiftKeyRedPacket userGiftKeyRedPacket : userGiftKeyRedPacketMap.values()) {
            if (userGiftKeyRedPacket.isUpdateOption()) {
                GiftKeyBussiness.updateUserGiftKeyRedPacket(userGiftKeyRedPacket);
            } else if (userGiftKeyRedPacket.isInsertOption()) {
                GiftKeyBussiness.addUserGiftKeyRedPacket(userGiftKeyRedPacket);
            }
        }
        return true;
    }

    /**
     * 结算红包
     * @param userGiftKeyRedPacket
     */
    public void getRedPacketReward(UserGiftKeyRedPacket userGiftKeyRedPacket) {
        if (userGiftKeyRedPacket.isGetIngots()) {
            return;
        }
        List<String> paramList = StringUtils.stringToStringList(StringUtils.stringToStringList(userGiftKeyRedPacket.getSettings(), "\\|").get(0), ",");
        // 如果是结算标识 则开始结算
        userGiftKeyRedPacket.setGetIngots(true);

        int sum = 0;
        for (int ingots : userGiftKeyRedPacket.getIngotsList()) {
            sum += ingots;
        }

        try {
            int minIngots = Integer.valueOf(paramList.get(5));
            if (sum <= minIngots && paramList.size() >= 6) {
                sum = minIngots;
            }
        } catch (Exception ex) {
            log.error("滑红包奖励兑换失败 uid : {}, gift key : {}", player.getUserId(), userGiftKeyRedPacket.getKey());
        }

        // 大于配置的上限 则使用配置的上限 否则以实际为准
        userGiftKeyRedPacket.setRealGetIngots(sum > Integer.valueOf(paramList.get(3)) ? Integer.valueOf(paramList.get(3)) : sum);

        // 投放超过2000元宝 不给
        if (userGiftKeyRedPacket.getRealGetIngots() > 2000) {
            return;
        }
        player.getModule(CurrencyModule.class).addCurrency(new Property(GameConfig.GAME_MONEY_INGOTS, BigInteger.valueOf(sum)), eLogMoneyType.Activity, eLogMoneyType.SlideRedPacket);
    }
}
